package com.jack.helloworld.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.jack.helloworld.R;

public class SharePreferenceActivity extends AppCompatActivity implements View.OnClickListener {

    EditText etUserName;
    EditText etPasswd;
    CheckBox cbSave;
    Button btnLogin;
    Button btnCancel;

    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_preference);

        initView();
        initData();
    }

    private void initView() {
        etUserName = (EditText) findViewById(R.id.etUserName);
        etPasswd = (EditText) findViewById(R.id.etPasswd);
        cbSave = (CheckBox) findViewById(R.id.cbSave);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnCancel = (Button) findViewById(R.id.btnCancel);
    }

    private void initData() {

        sharedPreferences = getSharedPreferences("userInfo", MODE_PRIVATE);
        editor = sharedPreferences.edit();

        String spUserName = sharedPreferences.getString("username", "");
        if (spUserName != null && !spUserName.equals("")) {
            etUserName.setText(spUserName);
            cbSave.setChecked(true);
        }

        btnLogin.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnLogin:
                String userName = etUserName.getText().toString().trim();
                String passWd = etPasswd.getText().toString().trim();
                if (userName.equals("admin") && passWd.equals("123456")) {
                    Toast.makeText(this, getString(R.string.loing_success), Toast.LENGTH_SHORT).show();
                    if (cbSave.isChecked()) {
                        Toast.makeText(this, R.string.save_userName, Toast.LENGTH_SHORT).show();
                        editor.putString("username", userName);
                        editor.commit();
                    } else {
                        Toast.makeText(this, R.string.delete_userName, Toast.LENGTH_SHORT).show();
                        editor.remove("username");
                        editor.commit();
                    }
                } else {
                    Toast.makeText(this, R.string.login_fail, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnCancel:
                break;
        }
    }
}
